//
//
//
amJumping = false;
templateCookiePrefix = "rt_";
templateApplyTarget = "/tmpo/form248/"


function getSiteCfg() { 
    $.getJSON(
        "/api/tmpo/config_public/",
        function(json) {
            var val = 'POC: <a class="POCemail" href="mailto:' +
                      json.tmpo_poc_email + '">' + json.tmpo_poc_name +
                      '</a> Phone: (' + json.tmpo_poc_phone.substr(0,3) +
                      ') ' + json.tmpo_poc_phone.substr(3,3) + '-' + 
                      json.tmpo_poc_phone.substr(6,4);
            $("span.POCemail").append(val); 
        }
    );
}


function getCommonLookups() {
    $.ajax({
        type: 'GET',
        url: '/api/tmpo/resources/',
        dataType: "json",
        success: function(json) {
            var val = '';
            drivers = json.drivers;
            $.each(drivers, function() {
	        val += '<input type="checkbox" value="' + this['id'] +
                       '" label="' + this['name'] + '" /> ' +
                       this['name'] + '<br />';
            });
            $("span[name='drivers']").append(val);
            val = '';
            vehicles = json.vehicles;
            $.each(vehicles, function() {
	        val += '<input type="checkbox" value="' + this['id'] +
                       '" label="' + this['vehicleno'] + '" /> ' +
                       this['vehicleno'] + '<br />';
            });
            $("span[name='vehicles']").append(val);
        },
        error: function() {
            window.location.href = "/tmpo/";
        },
        complete: function() {
            setProtoHTML();
            var val = $.qs('date') ? $.qs('date') : '';
            getDate(val);
            setJumpInput();
        }
    });
}


function setJumpInput() {
    $("#jumpday").focus(function (e) {
        $("#jumpday").val('');
    })

    $("#jumpday").keyup(function (e) {
        var v = $("#jumpday").val();
        var m = v.match(/^\s*(\d{1,2})\s+([a-zA-Z]{3,3})\s*$/i);
        if (m && !amJumping) {
            var y = new Date().getFullYear()
            var dt = new Date();
            var mo = convertMonth(m[2]);
            var dy = m[1];
            dt.setMonth(mo-1);
            dt.setDate(dy);
            if ((typeof mo != 'string') && dt.getMonth()==(mo-1) && dt.getDate()==dy) {
                mo = (mo < 10 ? "0" : "") + mo;
                dy = (dy.length == 1 ? "0" + dy : dy)
                amJumping = true;
                getDate("" + y + "-" + mo + "-" + dy);
            }
        } 
    })
}


function getDate(val) {
    $("#commitmentReportTable").remove();
    $("div.mainContent").append(proto_html['table']);
    var url = '/api/dates/';
    url += val ? val + '/' : '';
    $.getJSON(
        url,
        function(json) {
            var json = json['info'][0];
            $("#commitmentReportTable caption span a:eq(0)")
                .after('&nbsp;' + json['display'] + '&nbsp;');
            getCommitments(json['today'], json['previous'], json['next']);
            $("#jumpday").val(json['display'].slice(0,6));
            amJumping = false;
        }
    );
    getRequests();
    getConflicts();
}


function getCommitments(today,previous,next) {
    $.ajax({
        type: 'GET',
        url: '/api/tmpo/commitment/' + today + '/',
        dataType: "json",
        success: function(json) {
            if ( json.length ){
                writeCommitments(json, today);
            } else {
                $("#commitmentReportTable")
                    .append(proto_html['no_commitments']);
            }
        },
        complete: function() {
            $("#button_previous").click( function() {
                getDate(previous);
                return false;
            });
            $("#button_next").click( function() {
                getDate(next);
                return false;
            });
            $("#button_print").click( function() {
                makePrinter("#commitmentReportTable")();
                return false;
            }); 
            clearTemplateButtons();
	    makeTemplateMenu();
	    }

    });

}


function clearTemplateButtons () {
    $("a[id^=template_]").remove()
}


function makeTemplateMenu () {
    var startele = $("#button_248");
    var templates = getTemplateCookies();
    for (var templateName in templates) {
        var templateid = "template_" + templateName;
        if (!$("#"+templateid).length) {
            startele.after("<a id='" + templateid
                           + "' class='button' href='#'>Template:" + templateName
                           + "</a>");
            $("#"+templateid).showMenuClick({query:"#templateMenu", opacity:1.0})
            $("#"+templateid).click(function (e) {
                $("#templateMenu a:eq(0)").click(function (e) {
                    window.location.href = templateApplyTarget + "?ct=" + templateName
                    return false;
                })
                $("#templateMenu a:eq(1)").click(function (e) {
                    $.cookie(templateCookiePrefix+templateName, null, {path:"/"});
                    clearTemplateButtons();
	            makeTemplateMenu();
                })

            })
	}
    }
}


function getRequests() {
    $.getJSON(
        "/api/tmpo/commitment/requested/",
        function(json) {
            $("div#newRequests").html('');
            $.each(json, function() {
                var start = "9999-99-99 99:99:99";
                var finish = "0000-00-00 00:00:00";
                $.each(this['legs'], function() {
                    start = this['start'] < start ? this['start'] : start;
                    finish = this['finish'] > finish ? this['finish'] : finish;
                });
                start = $.y4m2d2_to_d2m3y4(start.substr(0,10));
                finish = $.y4m2d2_to_d2m3y4(finish.substr(0,10));
                var val = '<a href="/tmpo/form248/?commitment_id=' +
                          this['commitment_id'] + '">' + start;
                if ( start != finish ){
                    val += ' - ' + finish;
                }
                val += '. ' + this['org_req_name'] + '.</a><br />'; 
                $("div#newRequests").append(val);
            });
        }
    );
}


function getConflicts() {
    $.getJSON(
        "/api/tmpo/commitment/conflicted/",
        function(json) {
            $("div#alerts").html('');
            $.each(json, function() {
                var start = "9999-99-99 99:99:99";
                var finish = "0000-00-00 00:00:00";
                $.each(this['legs'], function() {
                    start = this['start'] < start ? this['start'] : start;
                    finish = this['finish'] > finish ? this['finish'] : finish;
                });
                start = $.y4m2d2_to_d2m3y4(start.substr(0,10));
                finish = $.y4m2d2_to_d2m3y4(finish.substr(0,10));
                var val = '<a href="/tmpo/form248/?commitment_id=' +
                          this['commitment_id'] + '">' + start;
                if ( start != finish ){
                    val += ' - ' + finish;
                }
                val += '. ' + this['org_req_name'] + '.</a><br />'; 
                $("div#alerts").append(val);
            });
        }
    );
}


function updateLegs(date) {
    var legs = $("tbody:has(:input[name='start_time'])");
    $.each(legs, function(i) {
        if( (i + 1) == legs.length ){
            var success = function() {
                getDate(date);
	    }	
	}else{
            var success = function() {}
	}
        $.ajax({
            type: "POST",
            url: '/api/tmpo/commitment/leg/' +
	         $(this).attr("commitment_leg_id") + '/',
            data: legData(this, date),
            dataType: "json",
	    success: success
        });
    });
}


function legData(leg, date) {
    var ret = {};

    var checkin = $(leg).find(":input[name='checkin']").val();
    ret['checkin'] = date + ' ' + checkin.substr(0,2) + ':' + checkin.substr(2,2);


    var start = $(leg).find(":input[name='start_time']").val();
    ret['start'] = date + ' ' + start.substr(0,2) + ':' + start.substr(2,2);
    var finish = $(leg).find(":input[name='finish_time']").val();
    ret['finish'] = date + ' ' + finish.substr(0,2) + ':' + finish.substr(2,2);
    ret['location'] = $(leg).find(":input[name='location']").val();
    //ret['poc_name'] = $(leg).find(":input[name='poc_name']").val();
    //ret['poc_phone'] = $(leg).find(":input[name='poc_phone']").val();
    ret['destination'] = $(leg).find(":input[name='destination']").val();
    ret['passengers'] = ( $(leg).find(":input[name='passengers']").val() )
                      ? $(leg).find(":input[name='passengers']").val()
		      : 0 ;
    ret['cargo'] = $(leg).find(":input[name='cargo']").val();
    ret['comment'] = $(leg).find(":input[name='comment']").val();
    var sel = $(leg).find("span[name='vehicles'] :checkbox:checked");
    var vehicles = ['0'];
    jQuery.each(sel, function(i, v) {
        vehicles[i+1] = $(this).val();
    });
    ret['vehicles'] = vehicles;
    sel = $(leg).find("span[name='drivers'] :checkbox:checked");
    var drivers = ['0'];
    jQuery.each(sel, function(i, v) {
        drivers[i+1] = $(this).val();
    });
    ret['drivers'] = drivers;
    return ret;
}


function writeCommitments(commitments, today) {
    jQuery.each(commitments, function() {
        var commitment = this;
        var add_days_legs = this['legs'];
        commitment['legs'] = $.grep(commitment['legs'], function(leg) {
            return leg['start'].substr(0,10) == today;
        });
        $("#commitmentReportTable").append(proto_html['commitment']);
        $("#commitmentReportTable tbody:last")
            .data("commitment", commitment)
            .hover(
                function() {
                    $(this).addClass('highlight');
                },
                function() {
                    $(this).removeClass('highlight');
                }
            )
            .find("td:first span.commitmentHeader")
            .html(retCommitmentDesc(commitment))
            .end()
            .find("td:first span:eq(0)")
            .click( function() {
                $(this).siblings("span.hoverButton").andSelf().hide();
                commitment['legs']['poc_name'] = commitment['poc_name'];
                commitment['legs']['poc_phone'] = commitment['poc_phone'];
                commitment['legs']['commitment_id'] = commitment['commitment_id'];
                writeEditLegs(commitment['legs'], today);
                return false;
            })
            .end()
            .find("td:first span:eq(2)")
            .click( function () { templatePrompt(commitment); return false ;} )
            .end()
            .find("td:first span:eq(1)")
            .click( function() {
                window.location.href = "/tmpo/form248/?commitment_id=" +
                                       commitment['commitment_id'];
                return false;
            });
        $("#commitmentReportTable").append(proto_html['column_headers']);

        writeShowLegs(commitment['legs']);
        $("#commitmentReportTable tbody:last")
            .find("tr:nth-child(1) td:nth-child(6)")
            .html( commitment['poc_name'] )
            .end()
            .find("tr:nth-child(1) td:nth-child(7)")
            .html( commitment['poc_phone'] )
            .end()

	writeAdditionalDays(add_days_legs, today);
    });
}


function getTemplateCookies() {
    var templateCookies = {};
    var cookies = document.cookie.split(";");
    for (var i=0; i<cookies.length; i++) {
        var cookie = $.trim(cookies[i]);
        if (cookie.substr(0, templateCookiePrefix.length)==templateCookiePrefix) {
            var parts = cookie.split("=");
            var key = parts[0].substr(templateCookiePrefix.length);
	    var value = parts[1];
            templateCookies[key] = value;
        }
    }
    return templateCookies;
}


function makeFailDialog() {
    $("#templateDialogFail").dialog({
        modal: true,
        height: 200,
        resizable: false,
        overlay : { opacity: 0.5, background:"#1b1e48" },
        open : function () {
            $(".ui-dialog button").attr("class", "button");
            $(".ui-dialog-buttonpane").css("padding", "1em");
            $(".ui-dialog-container")
                .append("<h2>Sorry!</h2>")
                .append("I can't create that template for you because it would break your access to the site.  To work around this problem, delete one or more of your existing templates.  I know this is lame, but it's a technical limitation that is out of our control.  Ten thousand apologies.")
        },
        buttons: {
        "OK" : function () {
                $("#templateDialogFail").dialog("destroy");
	    }

	}
    })
    $("#templateDialogFail").dialog("open");
}


function templatePrompt(commitment) {
    $("#templateDialog").dialog({
        modal : true,
        height : 100,
        resizable : false,
        overlay : { opacity: 0.5, background:"#1b1e48" },
        open : function () {
            $(".ui-dialog button").attr("class", "button");
            $(".ui-dialog-buttonpane").css("padding", "1em");
            $(".ui-dialog-container")
                .append("Give this template a name:")
                .append("<input type=text id=templateCopyName />");
        },
        buttons: {
	"OK" : function () {
                var name = $("#templateCopyName").attr("value")
                if (name) {
                    name = name.replace(/\W/g, "_");
                    var newc = $.toJSON(commitment);
		    if ((newc.length + document.cookie.length) < 8000) {
                        $.cookie(templateCookiePrefix+name, newc,
                                 {expires:6000, path:"/"})
                        clearTemplateButtons();
	                makeTemplateMenu();
		    } else {
                        $("#templateDialog").dialog("destroy");
                        makeFailDialog();
                        return;
                    }
		}
                $("#templateDialog").dialog("destroy");
            },
        "Cancel" : function () {
                $("#templateDialog").dialog("destroy");
	    }
        }
    });
    $("#templateDialog").dialog("open");

}


function writeShowLegs(legs) {
    jQuery.each(legs, function() {
        var leg = this;
        $("#commitmentReportTable").append(proto_html['leg_show']);
        var d_list = [];
        $.each(leg['drivers'], function() {
            var d = this;
            $.each(drivers, function() {
                if ( d == this['id'] ){
                    d_list[ d_list.length ] = this['name'];
                }
            });
        });
        d_list = d_list.length ? d_list.join(', ') : '';
        var v_list = [];
        jQuery.each(leg['vehicles'], function() {
            var v = this;
            $.each(vehicles, function() {
                if ( v == this['id'] ){
                    v_list[ v_list.length ] = this['vehicleno'];
                }
            });
        });
        v_list = v_list.length ? v_list.join(', ') : '';
        LEG=leg;
        $("#commitmentReportTable tbody:last")
            .attr("commitment_leg_id", leg['commitment_leg_id'])
            .find("tr:nth-child(1) td:nth-child(1)")
            .html( d_list )
            .end()
            .find("tr:nth-child(1) td:nth-child(2)")
            .html( v_list )
            .end()
            .find("tr:nth-child(1) td:nth-child(3)")
            .html( leg['checkin'].substr(11,2) + leg['checkin'].substr(14,2) )
            .end()
            .find("tr:nth-child(1) td:nth-child(4)")
            .html( leg['start'].substr(11,2) + leg['start'].substr(14,2) )
            .end()
            .find("tr:nth-child(1) td:nth-child(5)")
            .html( leg['finish'].substr(11,2) + leg['finish'].substr(14,2) )
            .end()
            //.find("tr:nth-child(1) td:nth-child(6)")
            //.html( this['poc_name'] )
            //.end()
            .find("tr:nth-child(1) td:nth-child(8)")
            .html( leg['location'] )
            .end()
            .find("tr:nth-child(1) td:nth-child(9)")
            .html( leg['destination'] )
            .end()
            .find("tr:nth-child(1) td:nth-child(10)")
            .html( leg['passengers'] )
            .end()
            .find("tr:nth-child(1) td:nth-child(11)")
            .html( leg['cargo'] )
            .end()
            .find("tr:nth-child(2) td:nth-child(1)")
            .append( leg['comment'] )
    });
}


function writeEditLegs(legs, today) {
    $("#commitmentReportTable tbody").unbind();
    var sel = "";
    jQuery.each(legs, function() {
        leg = this;
        sel = "#commitmentReportTable tbody[commitment_leg_id='" +
                  leg['commitment_leg_id'] + "']";
        var holder = $(sel).prev();
        $(sel).replaceWith(proto_html['leg_edit']);
        $(holder)
            .next()
            .attr("commitment_leg_id", leg['commitment_leg_id']);
        $(sel)
            .find(" :input[name='checkin']")
            .val( leg['checkin'].substr(11,2) + leg['checkin'].substr(14,2) )
            .end()
            .find(" :input[name='start_time']")
            .val( leg['start'].substr(11,2) + leg['start'].substr(14,2) )
            .end()
            .find(" :input[name='finish_time']")
            .val( leg['finish'].substr(11,2) + leg['finish'].substr(14,2) )
            .end()
            .find(" :input[name='poc_name']")
            .val( legs['poc_name'] )
            .end()
            .find(" :input[name='poc_phone']")
            .val( legs['poc_phone'] )
            .end()
            .find(" :input[name='location']")
            .val( leg['location'] )
            .end()
            .find(" :input[name='destination']")
            .val( leg['destination'] )
            .end()
            .find(" :input[name='passengers']")
            .val( leg['passengers'] )
            .end()
            .find(" :input[name='cargo']")
            .val( leg['cargo'] )
            .end()
            .find(" :input[name='comment']")
            .val( leg['comment'] );
        var span = sel + " span[name='drivers']";
        var labels = [];
        $.each(leg['drivers'], function() {
            var cb = $(span + " :checkbox[value='" + this + "']");
            $(cb).attr("checked","checked");
            labels[ labels.length ] = $(cb).attr('label');
        });
        labels = labels.length ? labels.join(', ') : 'None.';
        $(span).siblings("span[name='list']").html(labels);
        span = sel + " span[name='vehicles']";
        labels = [];
        $.each(leg['vehicles'], function() {
            var cb = $(span + " :checkbox[value='" + this + "']");
            $(cb).attr("checked","checked");
            labels[ labels.length ] = $(cb).attr('label');
        });
        labels = labels.length ? labels.join(', ') : 'None.';
        $(span).siblings("span[name='list']").html(labels);
    });
    $(sel).after(proto_html['buttons']);
    bindButtons(today, sel, legs['commitment_id']);
}


function writeAdditionalDays(legs,today) {
    var dates = [];
    $.each(legs, function() {
        if ( today != this['start'].substr(0,10) &&
	     $.inArray( this['start'].substr(0,10), dates ) == -1 
	  ){
	    dates[dates.length] = this['start'].substr(0,10);
	}
    });
//    console.debug(dates);
    if ( dates.length ){
        var val = '';
        $.each(dates, function(i, v) {
	    if ( i == 0 ){
	        val += '<a href="#" date="' + v + '">' +
		       $.y4m2d2_to_d2m3y4(v) + '</a>';
	    }else if ( i == ( dates.length - 1 ) ){
	        val += ' and <a href="#" date="' + v + '">' +
		       $.y4m2d2_to_d2m3y4(v) + '</a>';
	    }else{
	        val += ', <a href="#" date="' + v + '">' +
		       $.y4m2d2_to_d2m3y4(v) + '</a>';
	    }
        });
	val += '.';
        $("#commitmentReportTable").append(proto_html['additional']);
	$("#commitmentReportTable tbody:last")
	    .find("td:first")
	    .append(val);
	$.each(dates, function(i, v) {
	    $("a[date='" + v + "']").click( function() {
	        getDate(v);
	        return false;
	    });
	});
    }
}


function retCommitmentDesc(c) {
    var start = "9999-99-99 99:99:99";
    var finish = "0000-00-00 00:00:00";
    $.each(c['legs'], function() {
        start = this['start'] < start ? this['start'] : start;
        finish = this['finish'] > finish ? this['finish'] : finish;
    });
    var legs = ' &mdash; ' + c['legs'].length + ' leg(s): ' +
                   start.substr(11,2) + start.substr(14,2) + ' to ' +
                   finish.substr(11,2) + finish.substr(14,2);
    var ret = c['org_req_name'] + ' &mdash; POC: ' + c['poc_name'] + ', (' +
              c['poc_phone'].substr(0,3) + ')&nbsp;' + c['poc_phone'].substr(3,3) +
              '-' + c['poc_phone'].substr(6,4) + legs;
    return ret;
}

function updatePoc(selector, cid) {
    poc_name = $(selector).find(" :input[name='poc_name']").val();
    poc_phone = $(selector).find(" :input[name='poc_phone']").val();
    data = {poc_phone:poc_phone, poc_name:poc_name}
    $.ajax({
      type:'POST',
      url:'/api/tmpo/commitment/poc_details/' + cid + '/',
      dataType: 'json',
      data:data,
      success: function(json) {console.log("updatePoc OK", json)},
      error: function() {console.log("updatePoc FAIL")}
    })  

}




function bindButtons(today, selector, commit_id) {
    $("#button_save,#button_cancel").unbind();
    $("#button_save").click( function() {
        $("#button_save,#button_cancel").unbind();
	$(this).siblings("span").hide();
	$(this).siblings("span:eq(2)").show();
        if( !validateForm() ){
            updatePoc(selector, commit_id);
            updateLegs(today);
        } else {
            $(this).siblings("span").hide();
	    $(this).siblings("span:eq(1)").show();
            bindButtons(today, selector, commit_id);
        }
        return false;	
    });
    $("#button_cancel").click( function() {
        getDate(today);
        return false;
    });
    var sel = "span[name='drivers'], span[name='vehicles']";
    sel = $(sel).children(":checkbox");
    $(sel).unbind();
    $(sel).click( function() {
        var sel = $(this).parent().children(":checked");
        var labels = [];
        $.each(sel, function(i, v) {
            labels[i] = $(this).attr('label');
        });
        labels = labels.length ? labels.join(', ') : 'None.';
        $(this).parent().siblings("span[name='list']").html(labels);
    });
}


function validateForm() {
    var error_count = 0;
    $("span.inputErrorMessage").hide();
    $("td.inputError").removeClass("inputError");
    var legs = $("tbody:has(:input[name='start_time'])");
    var leg_fields = ['start_time','finish_time','location','destination'];
    $.each(legs, function() {
        var leg = this;
        $.each(leg_fields, function() {
            var f = $(leg).find(":input[name='" + this + "']");
            if( !$.trim( $(f).val() ) ){
                error_count++;
                $(f).parents("td:first").addClass("inputError")
                    .children("span.inputErrorMessage:eq(2)").hide().end()
                    .children("span.inputErrorMessage:eq(1)").hide().end()
                    .children("span.inputErrorMessage:eq(0)").show();
            }
        });
	var f = $(leg).find(":input[name='passengers']");
	if( $.trim( $(f).val() ) &&
	    !$(f).val().match(new RegExp('^[0-9]+$'))
	  ){
            error_count++;
            $(f).parents("td:first").addClass("inputError")
                .children("span:eq(0)").show();
	}
	var start_time = $(leg).find(":input[name='start_time']");
        if( $.trim( $(start_time).val() ) &&
	    !$.is_24hour( $(start_time).val() )
	  ){
            error_count++;
            $(start_time).parents("td:first").addClass("inputError")
                .children("span.inputErrorMessage:eq(0)").hide().end()
                .children("span.inputErrorMessage:eq(1)").show();
	}
	var finish_time = $(leg).find(":input[name='finish_time']");
        if( $.trim( $(finish_time).val() ) &&
	    !$.is_24hour( $(finish_time).val() )
	  ){
            error_count++;
            $(finish_time).parents("td:first").addClass("inputError")
                .children("span.inputErrorMessage:eq(0)").hide().end()
                .children("span.inputErrorMessage:eq(2)").hide().end()
                .children("span.inputErrorMessage:eq(1)").show();
	}
        if( $.is_24hour( $(start_time).val() ) &&
	    $.is_24hour( $(finish_time).val() ) &&
	    ( $(start_time).val() >= $(finish_time).val() )
	  ){
            error_count++;
            $(finish_time).parents("td:first").addClass("inputError")
                .children("span.inputErrorMessage:eq(0)").hide().end()
                .children("span.inputErrorMessage:eq(1)").hide().end()
                .children("span.inputErrorMessage:eq(2)").show();
	}   
    });
    return error_count;
}


function setProtoHTML() {    
    var proto_pre = {
        'commitment':'protoCommitmentRowHTML',
        'no_commitments':'protoNoCommitmentsRowHTML',
        'column_headers':'protoHeadersRowHTML',
        'leg_show':'protoShowRowHTML',
        'leg_edit':'protoEditRowHTML',
        'additional':'protoAdditionalLegsRowHTML',
        'buttons':'protoButtonsRowHTML',
        'table':'protoCommitmentReportTableHTML'
    };
    proto_html = {};
    jQuery.each(proto_pre, function(i, val) {
        proto_html[i] = $("#" + val).html();
        $("#" + val).remove();
    });

}


jQuery(function($) {
    getSiteCfg();
    getCommonLookups();

    $(":radio, :checkbox").css("border", "none");
    $("#logoutNavButton").click( function() {
        $.post("/api/logout/", {},
            function() {
                window.location.href = "/tmpo/";   
            }
        );
    });
    if ($.cookie("tmpoHome")) {
        $("img.headerLogo").parent().attr('href', $.cookie("tmpoHome"));
    }
});
